package com.cnwidsom.filter;

import java.util.ArrayList;
import java.util.List;

import com.cnwidsom.filter.Filter.BreakException;

public class DefaultFilterChain implements FilterChain {
	private List<Filter> registedFilters = new ArrayList<Filter>();
	private int index = 0;

	public DefaultFilterChain(FilterConfig[] filterConfigs) {
		if (filterConfigs != null) {
			for (int i = 0; i < filterConfigs.length; i++) {
				FilterConfig filterConfig = filterConfigs[i];
				try {
					Class filterClass = Class.forName(filterConfig.getFilterClassName());
					Filter filter = (Filter) filterClass.newInstance();
					if (!registedFilters.contains(filter)) {
						registedFilters.add(filter);
					}
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void doChain(Object obj) throws BreakException {
		try {
			if (index >= registedFilters.size()) {
				return;
			} else {
				registedFilters.get(index++).filter(this, obj);
			}
		} finally {
			index = 0;
		}
	}

	public void addFilter(FilterConfig filterConfig) {
		try {
			Class filterClass = Class.forName(filterConfig.getFilterClassName());
			Filter filter = (Filter) filterClass.newInstance();
			if (!registedFilters.contains(filter)) {
				registedFilters.add(filter);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
